package com.example.smartall.ui;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.smartall.R;
import com.example.smartall.adapter.PervasiveAdapter;
import com.example.smartall.api.Api;
import com.example.smartall.api.ApiConfig;
import com.example.smartall.api.NetCallBack;
import com.example.smartall.diaglog.LoadedDialog;
import com.example.smartall.entity.ActBannerBean;
import com.example.smartall.entity.ActListBean;
import com.example.smartall.entity.ActTypeBean;
import com.example.smartall.entity.JobDeliverHistoryBean;
import com.example.smartall.ui.base.BaseActivity;
import com.example.smartall.view.SListView;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.List;

/**
  * @Author:         abbas
  * @CreateDate:     2022/2/8
  * @Description: 在APP主页面上的各领域应用服务入口，点击“活动”图标信息，进入活动列表页面。
  * （1）列表页面包含：轮播图、活动分类、活动列表等三个部分。
  * （2）点击轮播图片可以跳转到活动详情页面，活动分类展示活动类别名称，活动列表依据最新发布时间排序，活动列表显示：活动图片、活动名称、报名人数、点赞数等；
  */
public class ActActivity extends BaseActivity {

    private ImageView imBack;
    private TextView tvTitle;
    private Banner banner;
    private TabLayout tabLayout;
    private SListView lv;

    private List<ActBannerBean.RowsBean> bannerBeans = new ArrayList<>();
    private List<String> bannerUrls = new ArrayList<>();
    private List<ActTypeBean.DataBean> typeBeans = new ArrayList<>();
    private List<ActListBean.RowsBean> listBeans = new ArrayList<>();
    private ActListAdapter listAdapter;

    private MHandler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_act);

        handler = new MHandler();

        init();
        initEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getBannerData();
        getActType();
    }

    @Override
    public void init() {
        imBack = (ImageView) findViewById(R.id.im_back);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        banner = (Banner) findViewById(R.id.banner);
        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        lv = (SListView) findViewById(R.id.lv);

        tvTitle.setText("活动管理");
    }

    @Override
    public void initEvent() {
        //返回键
        imBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActActivity.this.finish();
            }
        });

        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int i) {
                Intent intent = new Intent(ActActivity.this,ActDetailsActivity.class);
                intent.putExtra("id",listBeans.get(i).getId());
                startActivity(intent);
            }
        });

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                getActList("?categoryId="+tab.getTag());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(ActActivity.this,ActDetailsActivity.class);
                intent.putExtra("id",listBeans.get(i).getId());
                startActivity(intent);
            }
        });
    }

    private void getBannerData(){
        if (bannerBeans.size() > 0) return;
        Api.config(ApiConfig.ACT_BANNER,null).getRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                ActBannerBean bean = new Gson().fromJson(res,ActBannerBean.class);
                if (bean != null && bean.getCode() == 200){
                    bannerBeans = bean.getRows();
                    handler.sendEmptyMessage(0x01);
                }
            }

            @Override
            public void onFailure(Exception e) {

            }
        });
    }

    //获取活动类别
    private void getActType(){
        if (typeBeans.size() > 0) return;
        Api.config(ApiConfig.ACT_TYPE,null).getRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                ActTypeBean bean = new Gson().fromJson(res,ActTypeBean.class);
                if (bean != null && bean.getCode() == 200){
                    typeBeans = bean.getData();
                    handler.sendEmptyMessage(0x02);
                }
            }

            @Override
            public void onFailure(Exception e) {

            }
        });
    }

    //根据类别获取活动列表
    private void getActList(String target){
        LoadedDialog dialog = new LoadedDialog(getThis());
        dialog.show();

        Api.config(ApiConfig.ACT_LIST,null).getRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                dialog.dismiss();
                ActListBean bean = new Gson().fromJson(res,ActListBean.class);
                if (bean != null && bean.getCode() == 200){
                    listBeans = bean.getRows();
                    handler.sendEmptyMessage(0x03);
                }
            }

            @Override
            public void onFailure(Exception e) {
                dialog.dismiss();
            }
        },target);
    }

    class MHandler extends Handler{
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                //轮播图
                case 0x01:
                    for (ActBannerBean.RowsBean bean:bannerBeans) {
                        bannerUrls.add(ApiConfig.BASE_URL + bean.getAdvImg());
                    }
                    banner.setImages(bannerUrls);
                    banner.setImageLoader(new ImageLoader() {
                        @Override
                        public void displayImage(Context context, Object o, ImageView imageView) {
                            Glide.with(ActActivity.this).load(o).into(imageView);
                        }
                    });
                    banner.isAutoPlay(true);
                    banner.start();
                    banner.startAutoPlay();
                    break;
                case 0x02:
                    for (ActTypeBean.DataBean bean:
                         typeBeans) {
                        TabLayout.Tab tab = tabLayout.newTab();
                        tab.setText(bean.getName());
                        tab.setTag(bean.getSort());
                        tabLayout.addTab(tab);
                    }
                    tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
                    tabLayout.selectTab(tabLayout.getTabAt(0));
                    break;
                case 0x03:
                    if (listAdapter == null){
                        listAdapter = new ActListAdapter(listBeans);
                        lv.setAdapter(listAdapter);
                    }else {
                        listAdapter.setData(listBeans);
                    }
                    break;
            }
        }
    }

    class ActListAdapter extends PervasiveAdapter<ActListBean.RowsBean> {

        public ActListAdapter(List<ActListBean.RowsBean> data) {
            super(data);
        }

        @Override
        protected void setUI(ViewHolder holder, int position, Context context) {
            ImageView img = (ImageView) holder.getItemView(R.id.img);
            TextView title = (TextView) holder.getItemView(R.id.title);
            TextView subtitle = (TextView) holder.getItemView(R.id.subtitle);
            TextView content = (TextView) holder.getItemView(R.id.content);

            Glide.with(ActActivity.this).load(ApiConfig.BASE_URL + listBeans.get(position).getImgUrl()).into(img);
            title.setText(listBeans.get(position).getName());
            subtitle.setText("报名人数："+listBeans.get(position).getSignupNum());
            content.setText("点赞数：" + listBeans.get(position).getLikeNum());
        }

        @Override
        protected int getLayoutId() {
            return R.layout.common_list_item;
        }
    }
}